from pysqlite2 import dbapi2 as sqlite
from stemmer import PorterStemmer

stemmerObj = PorterStemmer()
db = sqlite.connect('database_final')

def Search(query):
	x = "select rowid from wordlist where word='" + query + "'"
	wordid = db.execute(x).fetchone()[0]
	
	if wordid == None:
		print "No Results Found\n"
		return 0
	
	y = "select urlid from linkword where wordid=" + str(wordid)
	listUrl = db.execute(y).fetchall( )
	count = 0
	print "Number of Search Results: " + str(len(listUrl))
	for i in listUrl:
		z = "select url from urllist where rowid=" + str(i[0])
		x = db.execute(z).fetchone()
		if x!= None:
			print x[0]
		count = count + 1
		if count == 20:
			break

def pageSearch(query):
	x = "select rowid from wordlist where word='" + query + "'"
	wordid = db.execute(x).fetchone()[0]
	
	count = 0

	if wordid == None:
		print "No Results Found\n"
		return 0

	for (urlid,) in db.execute('select urlid from pagerank where urlid in (select urlid from linkword where wordid=%d) order by score desc' % wordid):
		linker = db.execute('select url from urllist where rowid=%d' % urlid).fetchone()
		rank = db.execute("select score from pagerank where urlid=%d" % urlid).fetchone()
		print str(linker[0]) + "\t" + str(rank[0])
		count = count + 1
		if count == 20:
			break

def secpageSearch(query):
	x = "select rowid from wordlist where word='" + query + "'"
	wordid = db.execute(x).fetchone()[0]
	
	count = 0

	if wordid == None:
		print "No Results Found\n"
		return 0

	for (urlid,) in db.execute('select urlid from secPagerank where urlid in (select urlid from linkword where wordid=%d) order by score desc' % wordid):
		linker = db.execute('select url from urllist where rowid=%d' % urlid).fetchone()
		rank = db.execute("select score from secPagerank where urlid=%d" % urlid).fetchone()
		print str(linker[0]) + "\t" + str(rank[0])
		count = count + 1
		if count == 20:
			break

def wordSearch(query):
	x = "select rowid from wordlist where word='" + query + "'"
	wordid = db.execute(x).fetchone()[0]
	
	count = 0

	if wordid == None:
		print "No Results Found\n"
		return 0
	
	for (urlid,) in db.execute("select urlid from wordrank where urlid in (select urlid from linkword where wordid=%d) order by score desc" % wordid):
		linker = db.execute("select url from urllist where rowid=%d" % urlid).fetchone()
		rank = db.execute("select score from wordrank where urlid=%d" % urlid).fetchone()
		print str(linker[0]) + "\t" + str(rank[0])
		count = count + 1
		if count == 20:
			break

mode = input("Enter mode of search, 1 for Normal Search, 2 for PageRank, 3 for Secondary PageRank, 4 for WordRank: ")
query = raw_input("Enter the search keyword: ")

query = query.lower()
query = stemmerObj.stem(query,0,len(query)-1)

if mode==1:
	Search(query)
elif mode==2:
	pageSearch(query)
elif mode==3:
	secpageSearch(query)
elif mode==4:
	wordSearch(query)

